package com.binyouwei.udp_lib;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MulticastSender {

    public static void main(String[] args) {
        try {
            // 组播地址（选择一个在224.0.0.0至239.255.255.255之间的地址）
            InetAddress group = InetAddress.getByName("239.0.0.1");
            // 选择一个端口
            int port = 4446;
            // 消息内容
            String message = "Hello, this is a multicast message!";
            
            // 将消息转换为字节
            byte[] buffer = message.getBytes();
            
            // 创建DatagramPacket
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);
            
            // 创建MulticastSocket
            MulticastSocket socket = new MulticastSocket();
            
            // 发送数据包
            socket.send(packet);
            System.out.println("Message sent to the multicast group.");
            
            // 关闭socket
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
